import { ShelfPackage } from '@/api/Shelf';
import useCacheColumns from '@/hooks/useCacheColumns';
import { LeftClassTree } from '@/pages/boss/Listing/LeftClassTree';
import { PackageDetail, PackageDetailPorps } from '@/pages/boss/Listing/Package/Detail';
import { useAppSelector } from '@/redux/store';
import { useReactive } from 'ahooks';
import { App, Button, Drawer, Space, Spin } from 'antd';
import { useState } from 'react';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import { SelfPackageInfo } from '../interface';
type RecordType = ShelfPackage;

interface ListPorps {
  // 新增编辑事件
  onAddEdit?(value: SelfPackageInfo): void;
  // 打开弹窗事件
  onDetail?(): Promise<boolean>;
  // 删除事件
  onDelete?(): Promise<boolean>;
}

export function List({ onAddEdit }: ListPorps) {
  const { entId } = useAppSelector((state) => state.loginEnt);
  const { modal } = App.useApp();
  const detailsPorps = useReactive<{ props?: PackageDetailPorps }>({});
  const [extraParams, setExtraParams] = useState<{ classId?: string; parClassId?: string }>({
    classId: undefined,
    parClassId: undefined,
  });
  const [treeRefresh, setTreeRefresh] = useState<number>();
  const refreshTableAndTree = () => {
    setExtraParams((v) => ({ ...v }));
    setTreeRefresh(Math.random());
  };
  const [columns] = useState<YmColumnsType<RecordType>>([
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      width: 250,
    },
    {
      title: '修改时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
    },
    {
      title: '数量',
      dataIndex: 'num',
      key: 'num',
      width: 60,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (text, record) => {
        return (
          <Space direction="horizontal" size={0}>
            <Button
              type="text"
              size="small"
              onClick={(e: React.MouseEvent) => {
                onAddEdit?.({
                  guid: record.guid,
                  name: record.name,
                });
              }}
            >
              <span className="safe-edu_table_operation_text">编辑</span>
            </Button>
            <Button
              type="text"
              size="small"
              onClick={(e: React.MouseEvent) => {
                detailsPorps.props = {
                  guid: record.guid,
                  name: record.name,
                  createTime: record.createTime,
                  resourceType: '100',
                };
              }}
            >
              <span className="safe-edu_table_operation_text">详情</span>
            </Button>
            <Button
              type="text"
              size="small"
              onClick={(e: React.MouseEvent) => {
                modal.confirm({
                  title: '提示',
                  content: `确定要删除【${record.name}】吗`,
                  async onOk() {
                    await ShelfPackage.entDelete(record.guid);
                    refreshTableAndTree();
                  },
                });
              }}
            >
              <span className="safe-edu_table_operation_text">删除</span>
            </Button>
          </Space>
        );
      },
    },
  ]);

  const { handleColumns, onColumnsChange, loading } = useCacheColumns({
    checkType: 23,
    columns: columns!,
  });

  return (
    <div className="safe_boss_pagelr">
      <div className="safe_boss_page_left">
        <LeftClassTree
          value={extraParams.classId}
          onSelect={(classId, parClassId) => {
            setExtraParams((p) => ({ ...p, classId, parClassId }));
          }}
          refreshDeps={[treeRefresh]}
        ></LeftClassTree>
      </div>
      <div className="safe_boss_page_right">
        {loading ? (
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              height: '100vh',
            }}
          >
            <Spin spinning={loading}></Spin>
          </div>
        ) : (
          <YmTable
            searchForm={{
              formItems: [
                {
                  label: '名称',
                  name: 'name',
                  valueType: {
                    type: 'input',
                    inputProps: {
                      autoComplete: 'off',
                    },
                  },
                },
              ],
            }}
            toolBar={{
              onColumnsChange,
              prefixNode: (
                <Button
                  type="primary"
                  onClick={() => {
                    onAddEdit?.(extraParams);
                  }}
                >
                  新增
                </Button>
              ),
            }}
            columns={handleColumns}
            request={async ({ page }, form) => {
              const { current = 0, pageSize = 10 } = page ?? {};
              const data = await ShelfPackage.onPackageList(current, pageSize, {
                ...form,
                classId: extraParams.classId,
                entId,
              });
              return data;
            }}
            requestOptions={{
              reFreshDep: [extraParams],
              defaultPageSize: 20,
            }}
            rowKey="resourceId"
          ></YmTable>
        )}
      </div>
      <Drawer
        width={800}
        open={Boolean(detailsPorps.props)}
        title="详情"
        onClose={() => {
          detailsPorps.props = undefined;
        }}
      >
        {detailsPorps.props ? <PackageDetail {...detailsPorps.props} /> : null}
      </Drawer>
    </div>
  );
}
